import { Modal } from 'antd';
import { RadioGroup } from 'devextreme-react';
import TreeList, { Column, HeaderFilter, Toolbar } from 'devextreme-react/tree-list';
import React, { memo, useCallback, useImperativeHandle, useRef, useState } from 'react';
import { useModel } from 'umi';
import AntTabs from '~/public/cpas-ui/components-ui/ant-components/AntTab';
import {
  FinancialIndicatorsGet,
  mergeArrays,
  parseFormula,
  updateFinancialIndicators,
} from './server';
//@ts-ignore
import { deleteTable } from '@/pages/internalTran/service';
import { isValidExpression, nanoid10 } from '@/utils';
import notify from 'devextreme/ui/notify';
import DevPopup from '~/public/cpas-ui/components-ui/express-components/DevPopup';
import './index.less';
import PopupDevComponentsFormalu from './PopdevFormalu';
import PopupComponents from './Popup';

import getApiData from '@/services/cpasRequest';
import PopupChild from './PopupChildItem';
const Formula = React.forwardRef((props: any, ref: any) => {
  const priorities = ['证券公司', '商业银行'];
  // 正则表达式匹配 CP_CELL 函数中的第二个参数

  const tabs = ['传统行业指标（常用）', '传统行业指标（可选）', '金融业', '监管指标'];
  const { initialState } = useModel('@@initialState');
  const { dbname, sjnd } = initialState?.curPart;
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isFormulaModalOpen, setIsFormulaModalOpen] = useState('11');
  const [isUpdateCell, setIsUpdateCell] = useState(true);
  const [dataSourceOptions, SetDataSourceOptions] = useState<any>([]);
  //   const [CalculationFormulaSystem, setCalculationFormulaSystem] = useState('');
  const InputRefword = useRef<any>();
  // let editMode: any = 'cell';
  const [editMode, setditMode] = useState<any>('cell');
  const treeListRef = useRef<any>();
  const PopupChildRef = useRef<any>();
  const PopupComponentsRef = useRef<any>(null);
  const PopupComponentsFormulaRef = useRef<any>();
  const cpasTableFsRef = useRef<any>();
  const selectedKeys = useRef<any[]>([]);
  const DefaultselectedKeys = useRef<any[]>([]);
  const StoreData = useRef<any[]>([]);
  const rowIndex_data = useRef<any | boolean>(false);
  const isAudit = useRef<any>();
  const [activeTabKey, setActiveTabKey] = useState('传统行业指标（常用）');

  useImperativeHandle(ref, () => ({
    showPupop: async (items: any, data?: string) => {
      // currentTabid.current =
      rowIndex_data.current = false;
      isAudit.current = data?.includes('审定') ? '审定' : '未审';
      setActiveTabKey('传统行业指标（常用）');
      setIsModalOpen(true);
      const d = await FinancialIndicatorsGet({ dbName: dbname });
      StoreData.current = d.data;
      selectedKeys.current = [];
      DefaultselectedKeys.current = [];
      let item = d?.data?.filter(
        (a: any) => a.type === '1' && a.from_type === '传统行业指标（常用）',
      );
      if (item.length) {
        const ids = item.map((a: any) => a.IndicatorID);
        selectedKeys.current = ids; // 勾选

        DefaultselectedKeys.current = ids; // 勾选
      }
      SetDataSourceOptions(
        d?.data?.filter((a: { from_type: string }) => a.from_type.includes('传统行业指标（常用）')),
      );
      setTimeout(() => {
        treeListRef.current?.instance.selectRows(selectedKeys.current, true);
      }, 100);
    },
    handleCancel: () => {
      setIsModalOpen(false);
      // handleCancel
      Modal.destroyAll();
    },
  }));

  const onClickInitItem = async () => {
    const dd = await getApiData('CopyFinancialIndicators', { dbName: dbname });
    if (dd.ok) {
      const d = await FinancialIndicatorsGet({ dbName: dbname });
      StoreData.current = d.data;
      selectedKeys.current = [];
      let item = d?.data?.filter((a: any) => a.type === '1' && a.from_type === activeTabKey);
      if (item.length) {
        const ids = item.map((a: any) => a.IndicatorID);
        selectedKeys.current = ids; // 勾选
      }
      SetDataSourceOptions(
        d?.data?.filter((a: { from_type: string }) => a.from_type.includes(activeTabKey)),
      );
      setTimeout(() => {
        treeListRef.current?.instance.selectRows(selectedKeys.current, true);
      }, 100);
    } else {
      notify('初始化失败', 'error', 1000);
    }
    console.log(dd);
  };

  const onClickSave = async (e: any) => {
    // treeListRef.current?.instance.clearFilter()
    await treeListRef.current?.instance.saveEditData();
    let insertData = await treeListRef.current?.instance.getDataSource().items(); // 取不全

    let uniunItems = insertData.map((e: any) => e.data.IndicatorName);
    function findDuplicates(arr: any) {
      return arr.filter((item: any, index: any) => arr.indexOf(item) !== index);
    }
    let exits = [...new Set(findDuplicates(uniunItems))];

    if (exits.length) {
      notify(`${exits.toString()}-项目名字重复,请修改`, 'error', 3000);
      return;
    }
    // return;
    // 保存的逻辑
    // 读取时间列表，安装勾选的项目去更新，financial 表全部更新，删除和编辑 或者新增，
    //design表只更新选的，项目列，勾线的项目列中去增删改，cpastable的接口
    // 参考内存往来的逻辑，存在新增后有编辑的现象
    // 还要维护一个最新的表数组，financial 表每次删除更新。design表复杂点

    let check_ManualOrAutomatic = insertData.filter(
      (a: any) => !a.data?.ManualOrAutomatic && a.data.TaskIndicatorID_Parent_ID !== '0',
    );
    if (check_ManualOrAutomatic.length) {
      let name = check_ManualOrAutomatic.map((a: any) => a.data.IndicatorName);
      notify(`${name.toString()}项目,请设置计算方式自动或手动`, 'error', 3000);
      return;
    }
    let selectItems = treeListRef.current?.instance.getSelectedRowsData();
    selectItems = selectItems.map((e: any) => e.IndicatorID);
    let dd = await deleteTable({
      dbname: dbname,
      tableName: 'FinancialIndicators',
      from_type: activeTabKey,
    });
    if (!dd?.ok) {
      notify('保存失败', 'error', 2000);
      return;
    }
    return await updateFinancialIndicators(
      dbname,
      insertData.map((a: any, c: number) => {
        return {
          ...a.data,
          rowState: 'insert',
          from_type: activeTabKey,
          type: selectItems.includes(a.data.IndicatorID) ? '1' : '0',
          RowID: c + (activeTabKey.includes('可选') ? 10000 : 0),
        };
      }),
    );
  };

  const onClickOKandre = async () => {
    await onClickSave(1);
    let insertData = await treeListRef.current?.instance.getDataSource().items(); // 取不全
    let selectItems = treeListRef.current?.instance.getSelectedRowsData();
    selectItems = selectItems.map((e: any) => e.IndicatorID);
    if (selectItems.length === 0 && insertData.length && activeTabKey.includes('常用')) {
      notify('请勾线项目', 'error', 1000);
      return;
    }

    if (activeTabKey === tabs[0]) {
      // selectItems =treeListRef.current?.instance.getSelectedRowsData()
      // selectItems=selectItems.map((e:any)=>e.IndicatorID)
      // 取接口
      let arr_option = StoreData.current.filter(
        (a: { from_type: string; TaskIndicatorID_Parent_ID: string; type: string }) =>
          a.from_type?.includes(tabs[1]) && a.type === '1',
      );
      //insertData 带顺序
      selectItems = mergeArrays(
        insertData
          .filter((c: any) => selectItems.includes(c.data.IndicatorID))
          .map((a: any) => a.data),
        arr_option,
      );
    } else {
      // selectItems =treeListRef.current?.instance.getSelectedRowsData()
      // selectItems=selectItems.map((e:any)=>e.IndicatorID)
      let arr_option = StoreData.current.filter(
        (a: { from_type: string; TaskIndicatorID_Parent_ID: string; type: string }) =>
          a.from_type?.includes(tabs[0]) && a.type === '1',
      );
      selectItems = mergeArrays(
        arr_option,
        insertData
          .filter((c: any) => selectItems.includes(c.data.IndicatorID))
          .map((a: any) => a.data),
      );
    }
    setIsModalOpen(false);
    props.AddItemOKcallback(selectItems, activeTabKey);
  };
  // useEffect(() => {
  //   if (editMode === 'popup') {
  //     treeListRef.current?.instance?.addRow(rowIndex_data.current?.key);
  //   }
  // }, [editMode]);

  const saveItem = async (e: any) => {
    SetDataSourceOptions(
      dataSourceOptions.concat({
        IndicatorName: e.itemName,
        TaskIndicatorID_Parent_ID: rowIndex_data.current?.key,
        IndicatorID: nanoid10(),
        CalculationFormulaSystem: e.CalculationFormulaSystem,
        CalculationFormula: e.CalculationFormula,
        ManualOrAutomatic: e.action,
        IndicatorAnalysisTips: e.tip,
      }),
    );
    setTimeout(async () => {
      let d = await onClickSave(1);
      if (d?.success) {
        PopupChildRef.current.closePop();
        notify('保存成功', 'success', 2000);
      } else {
        notify('保存失败', 'error', 2000);
      }
    }, 500);
  };
  const onClickAdd = () => {
    if (rowIndex_data.current?.row?.level <= 0) {
      PopupChildRef.current.showPop();
    } else {
      notify('请先选中父项目', 'error', 2000);
    }
  };
  const onClickPaentItemAdd = async (e: any) => {
    //    debugger
    try {
      if (!treeListRef.current?.instance.hasEditData()) {
        InputRefword.current.show({
          title: `输入父项目名称`,
          okCallback: async (v: any, b: any) => {
            if (dataSourceOptions.filter((a: any) => a.IndicatorName === v?.trim()).length) {
              notify('父项目已经存在', 'error', 2000);
              return false;
            } else {
              SetDataSourceOptions(
                dataSourceOptions.concat({
                  IndicatorName: v,
                  TaskIndicatorID_Parent_ID: '0',
                  IndicatorID: nanoid10(),
                }),
              );
              setTimeout(async () => {
                let d = await onClickSave(1);
                if (d?.success) {
                  notify('保存成功', 'success', 2000);
                } else {
                  notify('保存失败', 'error', 2000);
                }
              }, 500);

              return true;
            }
          },

          value: '',
        });
      } else {
        notify(`当前编辑模式请先保存`, 'error', 2000);
      }
    } catch (e) {
      console.log(e);
    }
  };
  const onClickDelete = () => {
    let selectItems: any[] = treeListRef.current?.instance
      .getSelectedRowsData()
      .map((a: any) => a.IndicatorID);
    if (!treeListRef.current?.instance.hasEditData()) {
      if (selectItems.length) {
        // || rowIndex_data.current?.rowIndex >= 0
        // treeListRef.current?.instance?.deleteRow(rowIndex_data.current?.rowIndex);
        // treeListRef.current?.instance.saveEditData();
        // !treeListRef.current?.instance.hasEditData()

        SetDataSourceOptions(
          dataSourceOptions.filter((a: any) => !selectItems.includes(a.IndicatorID)),
        );
        setTimeout(async () => {
          let d = await onClickSave(1);
          if (d?.success) {
            notify('保存成功', 'success', 2000);
          } else {
            notify('保存失败', 'error', 2000);
          }
        }, 500);
      } else {
        notify(`请选中项目`, 'error', 2000);
      }
    } else {
      notify(`当前编辑模式请先保存`, 'error', 2000);
    }
  };
  // const onClickUpdate = () => {
  //     console.log("li", 1)
  //     setIsUpdateCell(true)
  // }
  const onCellClick = (e: any) => {
    console.log('li', e);
    rowIndex_data.current = e;
  };

  const onEditingStart = (e: any) => {
    if (activeTabKey.includes('行业指标')) {
      if (e.data.TaskIndicatorID_Parent_ID.toString() === '0') {
        if (e.column?.caption?.includes('项目')) {
        } else {
          e.cancel = true;
          notify('父项目不能编辑', 'error', 1000);
        }
      }
    }
  };
  const onCellDblClickFormula = async (e: any) => {
    const { column, data } = e;
    // 类型自动
    if (activeTabKey.includes('行业指标')) {
      if (column?.caption?.includes('计算公式')) {
        if (data.TaskIndicatorID_Parent_ID.toString() !== '0') {
          // setIsFormulaModalOpen(true);
          // CalculationFormulaSystemRef.current.initState('');
          if (data?.ManualOrAutomatic !== '手动') {
            PopupComponentsFormulaRef.current.show({
              title: '输入公式',
              isAudit: isAudit.current,
              cancelText: '取消',
              okText: '确定',
              IndicatorName: data.IndicatorName ? data.IndicatorName : '',
              rowCalculationFormulaSystem: data.CalculationFormulaSystem,
              // CalculationFormulaSystem: data.CalculationFormula_old_year,
              width: '80%',
              height: '100%',
              okCallback: async () => {
                // setIsFormulaModalOpen(false);
                handleOk();
              },
              cancelCallback: () => {
                // setIsFormulaModalOpen(false);
                // CalculationFormulaSystemRef.current.initState('');
              },
            });
          }
        } else {
          notify('父项目不能添加公式', 'error', 1000);
        }
      }
    }
  };

  const onCellHoverChanged = (e: any) => {
    // console.log('li', e)
  };
  const onReorder = useCallback(
    (e: any) => {
      const visibleRows = e.component.getVisibleRows();
      const newTasks = [...dataSourceOptions];

      const toIndex = newTasks.findIndex(
        (item: any) => item.IndicatorID === visibleRows[e.toIndex].data.IndicatorID,
      );
      const fromIndex = newTasks.findIndex(
        (item: any) => item.IndicatorID === e.itemData.IndicatorID,
      );

      newTasks.splice(fromIndex, 1);
      newTasks.splice(toIndex, 0, e.itemData as never);

      SetDataSourceOptions(newTasks);
    },
    [dataSourceOptions],
  );

  // 递归解析表达式

  const handleOk = async () => {
    // 更新单元格
    const CalculationFormulaSystem =
      PopupComponentsFormulaRef.current.getCalculationFormulaSystem();

    const CalculationFormulaSystemRe = CalculationFormulaSystem.replaceAll('期末_', '')
      .replaceAll('期初_', '')
      .replaceAll('本期_', '')
      .replaceAll('上期_', ''); //表名区分跨区间公式，但是字段还是要在存系统公式之前去掉

    if (isValidExpression(CalculationFormulaSystem) === '合法') {
      await treeListRef.current?.instance.cellValue(
        rowIndex_data.current?.rowIndex,
        'CalculationFormulaSystem',
        CalculationFormulaSystemRe,
      ); // 系统存储的公式，从新做公式，老的公式丢失信息
      await treeListRef.current?.instance.cellValue(
        rowIndex_data.current?.rowIndex,
        'CalculationFormula',
        parseFormula(CalculationFormulaSystem).replaceAll('行|标签聚合|合计|', ''),
      ); // 展示的公式，要简洁，去掉统计行，去掉cp，加载期初和期末的区分
    } else {
      notify(isValidExpression(CalculationFormulaSystem), 'error', 2000);
    }
  };
  const ConDiv = () => {
    return <>数据修改，未保存。是否保存？</>;
  };

  // 当输入框内容发生变化时，更新状态

  const handleCancel = () => {
    if (treeListRef.current?.instance.hasEditData()) {
      PopupComponentsRef.current.show({
        title: '提示信息',
        content: ConDiv,
        cancelText: '否',
        okText: '是',
        okCallback: async () => {
          // await onClickSave();
          setIsModalOpen(false);
          Modal.destroyAll();
        },
        cancelCallback: () => {
          setIsModalOpen(false);
          Modal.destroyAll();
        },
      });
    } else {
      setIsModalOpen(false);
      Modal.destroyAll();
    }
  };

  const onClickTabChange = async (e: any) => {
    debugger;
    // currentTabid.current =e
    setActiveTabKey(e);
    const d = await FinancialIndicatorsGet({ dbName: dbname });
    if (e.includes('传统行业指标')) {
      if (treeListRef.current?.instance.hasEditData()) {
        PopupComponentsRef.current.show({
          title: '提示信息',
          content: ConDiv,
          cancelText: '否',
          okText: '是',
          okCallback: async () => {
            // await onClickSave();
          },
          cancelCallback: () => {
            SetDataSourceOptions(
              StoreData.current.filter(
                (a: { from_type: string; TaskIndicatorID_Parent_ID: string }) =>
                  a.from_type?.includes(e) || a.TaskIndicatorID_Parent_ID === '0',
              ) as never[],
            );

            setTimeout(() => {
              treeListRef.current?.instance.selectRows(
                StoreData.current
                  .filter(
                    (a: { from_type: string; TaskIndicatorID_Parent_ID: string; type: string }) =>
                      a.type === '1' && a.from_type?.includes(e),
                  )
                  .map((I: any) => I.IndicatorID),
                true,
              );
            }, 100);
          },
        });
      } else {
        debugger;

        const data = d.data.filter((a: { from_type: string; TaskIndicatorID_Parent_ID: string }) =>
          a.from_type?.includes(e),
        ) as never[];
        SetDataSourceOptions(data);
        setTimeout(() => {
          treeListRef.current?.instance.selectRows(
            StoreData.current
              .filter(
                (a: { from_type: string; TaskIndicatorID_Parent_ID: string; type: string }) =>
                  a.type === '1' && a.from_type?.includes(e),
              )
              .map((I: any) => I.IndicatorID),
            true,
          );
        }, 100);
      }
    } else {
      // const d = await FinancialIndicatorsGet({ dbName: dbname });
      debugger;
      const res = d.data.filter(
        (a: { from_type: string; TaskIndicatorID_Parent_ID: string; type: string }) =>
          a.from_type?.includes(e),
      ) as never[];
      if (e === '监管指标') {
        // 进入默认证劵公司
        const result = res.filter((a: any) => {
          var utf8Encoded = new TextEncoder().encode(a?.type);

          // 打印出编码后的字节序列
          console.log(utf8Encoded);
          return a?.type == '证券公司';
        });
        SetDataSourceOptions(result);
      } else {
        SetDataSourceOptions(res);
      }
    }
  };
  const onSelectionChanged = ({ currentDeselectedRowKeys }: any) => {
    debugger;
    if (currentDeselectedRowKeys?.length) {
      // 1，父项目取消全部子项目取消
      let leng: any = dataSourceOptions.filter(
        (a: any) => a.TaskIndicatorID_Parent_ID === currentDeselectedRowKeys[0],
      );
      selectedKeys.current = selectedKeys.current.filter(
        (a: any) => a.IndicatorID === currentDeselectedRowKeys[0],
      );
      if (leng.length) {
        leng = leng.map((c: any) => c.IndicatorID);
        treeListRef.current?.instance.deselectRows(leng);
        // selectedKeys.current=selectedKeys.current.filter((a:any)=> leng.includes(a.IndicatorID))
      }
    }
    // treeListRef.current?.instance.saveEditData()
    // treeListRef.current?.instance.cellValue(1, 'type',currentTabid.current)
    // treeListRef.current?.instance.saveEditData()
  };

  const cellRender = (cellData: any) => {
    const tooltipContent = () => `详细信息: ${cellData.value}`;

    return <div id={`item_${cellData.key}`}>{cellData.value}</div>;
  };

  const onClickCompanyChange = async (e: any) => {
    debugger;
    const d = await FinancialIndicatorsGet({ dbName: dbname });
    if (d.data?.length) {
      SetDataSourceOptions(
        d.data.filter(
          (a: { from_type: string; TaskIndicatorID_Parent_ID: string; type: string }) =>
            a.from_type?.includes('监管指标') && a?.type === e,
        ) as never[],
      );
    }
  };
  const PopcontentRender = (a: any) => {
    console.log(a, 'li');
    return <>1</>;
  };
  const onClickSaveCHild = () => {
    console.log(treeListRef, 'treeListRef');
    // setIsFormulaModalOpen('wew');
  };
  const onClose = () => {
    setditMode('cell');
  };
  const popupOptions = {
    title: '输入子项目',
    showTitle: true,
    width: 700,
    colCount: 0,
    height: 500,
    onHiding: () => onClose(), // x的关闭
    formData: null,
    colSpan: 1,
    visible: true,
    name: 'ewwewe',
    toolbarItems: [
      {
        widget: 'dxButton',
        toolbar: 'bottom',
        location: 'after',
        options: { text: '保存', type: 'default', onClick: onClickSaveCHild },
      },
      { widget: 'dxButton', location: 'after', toolbar: 'bottom', options: { text: '取消' } },
    ],
    // contentRender: PopcontentRender,
  };
  const insertRow = (e: any) => {
    if (e.data.IndicatorName?.trim().length) {
    } else {
      e.cancel = true;
      notify('项目名字不能为空', 'error', 1000);
    }
  };

  const MonoFormaulList = memo(({ b }: any) => {
    return (
      //@ts-ignore
      <TreeList
        dataSource={dataSourceOptions}
        ref={treeListRef}
        showBorders={true}
        columnAutoWidth={true}
        // wordWrapEnabled={true}
        allowColumnResizing={true}
        onCellHoverChanged={onCellHoverChanged}
        onCellClick={onCellClick}
        // onRowClick={onCellClick}
        rootValue={b <= 1 ? '0' : ''}
        newRowPosition={'viewportTop'}
        height={550}
        width={'86vw'}
        onRowRemoved={() => console.log('li', 'de')}
        onRowInserting={insertRow}
        autoExpandAll={true}
        onSelectionChanged={onSelectionChanged}
        onCellDblClick={onCellDblClickFormula}
        rowDragging={{
          allowReordering: true,
          onReorder: onReorder,
        }}
        editing={{
          mode: editMode,
          allowUpdating: isUpdateCell,
          startEditAction: 'dblClick',
          popup: popupOptions,
        }}
        // defaultSelectedRowKeys={selectedKeys}
        selection={{
          mode: 'multiple',
        }}
        scrolling={{
          mode: 'standard',
        }}
        onEditingStart={onEditingStart}
        keyExpr="IndicatorID"
        parentIdExpr="TaskIndicatorID_Parent_ID"
        id="tasks"
        paging={{
          enabled: false,
          pageSize: 0,
        }}
        hoverStateEnabled={true}
        showRowLines={true}
        focusedRowEnabled={true}
      >
        {b <= 1 ? (
          <Toolbar
            items={[
              {
                disabled: dataSourceOptions.length,
                widget: 'dxButton',
                options: {
                  text: '初始化',
                  onClick: onClickInitItem,
                },
              },
              {
                widget: 'dxButton',
                options: {
                  text: '增加父项目',
                  onClick: onClickPaentItemAdd,
                },
              },
              {
                widget: 'dxButton',
                options: { text: `增加子项目`, onClick: onClickAdd },
              },
              {
                widget: 'dxButton',
                options: { text: '删除', onClick: onClickDelete },
              },

              // {
              //   widget: 'dxButton',
              //   showText: '',
              //   options: { text: '保存', onClick: onClickSave, type: 'default' },
              // },
            ]}
          ></Toolbar>
        ) : (
          <></>
        )}
        <HeaderFilter visible={true} />
        {/* <Selection mode="multiple" /> */}
        {/* <ColumnChooser enabled={true} /> */}

        <Column
          dataField="IndicatorName"
          width={250}
          caption="项目"
          cellRender={cellRender}
          allowSorting={false}
          validationRules={[
            {
              message: '必填',
              type: 'required',
            },
          ]}
          formItem={{
            colSpan: 2,
            // onCellClick: () => {
            //   debugger;
            // },
          }}
        />
        {activeTabKey.includes('监管') ? (
          <Column
            dataField="WarningLevel"
            width={250}
            caption="预警标准"
            cellRender={cellRender}
            allowSorting={false}
            // visible={activeTabKey.includes('监管')}
          />
        ) : (
          ''
        )}
        {activeTabKey.includes('监管') ? (
          <Column
            dataField="RegulatoryLevel"
            width={250}
            caption="监管标准"
            cellRender={cellRender}
            allowSorting={false}
            // visible={activeTabKey.includes('监管')}
          />
        ) : (
          ''
        )}

        <Column
          dataField="CalculationFormula"
          caption="计算公式"
          allowEditing={true}
          validationRules={[
            {
              message: '必填',
              type: 'required',
            },
          ]}
          editorOptions={{
            with: '90%',
            value: '手动',
          }}
          formItem={{
            colSpan: 2,
            with: '90%',
            // editorType: 'dxTextArea',
            editorOptions: {
              with: '90%',
              value: isFormulaModalOpen,
            },
            // onCellClick: () => {
            //   debugger;
            // },
          }}
        />
        {/* <Column
          dataField="CalculationFormulaSystem"
          caption="系统取数计算公式"
          allowEditing={false}
          visible={false}
          editorOptions={{
            onCellClick: () => {
              debugger;
            },
          }}
          formItem={{
            colSpan: 2,
            editorOptions: {
              onValueChanged: () => {
                debugger;
              },
            },
          }}
        /> */}

        <Column
          dataField="ManualOrAutomatic"
          caption="手动/自动"
          // dataType={}
          width={60}
          lookup={{
            dataSource: ['自动', '手动'],
            // displayExpr:'自动'
          }}
          minWidth={100}
          editorOptions={{
            value: '手动',
            // onValueChanged: () => {
            //   // debugge  r;
            // },
          }}
          formItem={{
            colSpan: 2,
            editorOptions: {
              // onValueChanged: (e: any) => {
              //   // if (e.value === '自动') {
              //   //   PopupComponentsFormulaRef.current.show({
              //   //     title: '输入公式',
              //   //     isAudit: isAudit.current,
              //   //     cancelText: '取消',
              //   //     okText: '确定',
              //   //     IndicatorName: '',
              //   //     rowCalculationFormulaSystem: '',
              //   //     // CalculationFormulaSystem: data.CalculationFormula_old_year,
              //   //     width: '80%',
              //   //     height: '100%',
              //   //     okCallback: async () => {
              //   //       // setIsFormulaModalOpen(false);
              //   //       handleOk();
              //   //     },
              //   //     cancelCallback: () => {
              //   //       // setIsFormulaModalOpen(false);
              //   //       // CalculationFormulaSystemRef.current.initState('');
              //   //     },
              //   //   });
              //   // }
              // },
            },
          }}
          // validationRules={[
          //   {
          //     message: '必填',
          //     type: 'required',
          //   },
          // ]}
        />
        <Column
          dataField="IndicatorAnalysisTips"
          caption="指标分析提示"
          width={300}
          formItem={{
            colSpan: 2,
            editorType: 'dxTextArea',
          }}
          minWidth={100}
          allowResizing={true}
        />
      </TreeList>
    );
  });
  return (
    <>
      <Modal
        zIndex={1000}
        open={isModalOpen}
        onCancel={handleCancel}
        // footer={null}
        onOk={onClickOKandre}
        width={'90vw'}
        // height={'90vh'}
        maskClosable={false}
        destroyOnClose={true}
      >
        <AntTabs
          defaultActiveKey="0"
          className="changeTabsHeight"
          type="editable-card"
          destroyInactiveTabPane={true}
          onChange={onClickTabChange}
          activeKey={activeTabKey}
          onEdit={() => {}}
          hideAdd={true}
        >
          {tabs.map((a: any, b: any) => (
            <AntTabs.TabPane key={a} tab={`${a}`} antTabsData={false} closable={false}>
              {b === 3 ? (
                <RadioGroup
                  style={{ a: 1 }}
                  items={priorities}
                  defaultValue={priorities[0]}
                  onValueChange={onClickCompanyChange}
                  layout="horizontal"
                />
              ) : (
                <></>
              )}

              <MonoFormaulList b={b}></MonoFormaulList>
              <DevPopup.Input ref={InputRefword} okText={'保存'} />
            </AntTabs.TabPane>
          ))}
        </AntTabs>
      </Modal>
      <PopupComponents ref={PopupComponentsRef} />
      <PopupDevComponentsFormalu ref={PopupComponentsFormulaRef} width={800} height={'70%'} />
      <PopupChild ref={PopupChildRef} saveItem={saveItem} dataSourceOptions={dataSourceOptions} />
    </>
  );
});
export default Formula;
